#加载训练及评估数据集

import pandas as pd
data_file =''
dataest =pd.read_csv(data_file)
print(dataest)
# dataest.info()

#数据预处理（删除列、补充缺省值、删除无效值）

#删除name、ticket、room列
dataset.drop(['name','ticket','room'],inplace=True,axis=1)
#补充age缺失值
dataset['age']=dataset['age'].fillna(dataset['age'].mean())
#删除有缺失值的所有行
dataset = dataset.dropna()

#定量化(手动、原生)

#定量化（pclass、sex、embarked)
labels =dataset['pclass'].unique.tolist()
dataset['pclass']=dataset['pclass'].apply(lambda x:labels.inde(x))
dataset['sex']=(dataset['sex']=='male').astype(int)
labels=dataset['embarked'].unique().tolist()
dataset['embarked']=dataset['embarked'].apply(lambda x:labels.index(x))
print(dataset)
dataset.info()

#定量化(编码器)
from sklearn.preprocessing import OrdinalEncoder 
encoder = OrdinalEncoder 
dataset[['pclass','sex','embarked']] = encoder.fit_transform(dataset[['pclass','sex', "embarked"]])
print (dataset) 
dataset.infoo

#提取特征及标签，并分割数据集

from sklearn.model_selection import train_test_split
x =dataset.iloc[:,:4].values
y =dataset.iloc[:,:4].values
x_train,x_test,y_train,y_test = train_test_split(x,y,random_state=1,test_set=0.2)
print(x,shape)


#寻找最优值参考值
from sklearn.ensemble import RandomForestclassifier 
from sklearn.metrics import accuracy_score 
from sklearn. model_selection import train_test_split 
import matplotlib.pyplot as plt
scores =[]
n_ranges = range(1, 201, 10)

for i in n_ranges:
    model= RandomForestclassifier(random_state=0, n_estimators=i) 
    model.fit(x_train,y_train) 
    pred = model.predict(x_test) 
    ac= accuracy_score(y_test, pred) 
    scores.append(ac) 

max_score = max(scores) 
print('f最大预测准确率:[max_score]') 
n= scores.index(max_score)*10 +1
print(f'对应的参数值为:n') 
plt.plot(n_ranges, scores) 
plt.show()

#训练随机森林模型

from sklearn.metrics import classification_report 
model =RandomForestclassifier(random_state=0, n_estimators=41) 
model.fit(x_train, y_train) 
pred= model.predict(x_test) 
re = classification_report(y_test, pred) 
print(re) 

#加载预测数据集
test_file='C:\Users\user_pmJLQ6pdf\Desktop'
test_set = pd.read_csv(test_file) 
#print(test_set) 
test_set.info()

#对测试集进行数据预处理

#定量化(pclass、sex、embarked) 
labels = test_set['pclass'].unique().tolisto 
test_set['pclass']- test_set['pclass'].apply(lambda x: labels.index(x)) 
test_set['sex']=(test_set['sex']=='male').astype(int) 
labels - test_set['embarked'].unique().tolist()
test_set['embarked']= test_set['embarked'].apply(lambda x: labels.index(x)) 
print(test_set) 
test_set.info()